package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import bean.Employee;


public class EmployeeDAO extends DAO<Employee> {
	public EmployeeDAO(SessionFactory factory) {
		super(factory);
	}	

	public ArrayList<String> createEmployee(Employee employee) {
		ArrayList<String> errors = new ArrayList<String>();
		Transaction tx = null;
		Session session = null;
		try {				
			session = this.getSession();
			tx = session.beginTransaction();
			session.save(employee);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)	tx.rollback();
			e.printStackTrace();
			errors.add(e.getMessage());
			return errors;
		} finally {
			if(session != null)	session.close();
		}
		return errors;
	}
	
	public Employee lookUpByUsername(String name) {
		List<Employee> list = this.getByAttribute("username", name, Employee.class);
		if (list != null && list.size() > 0) {
			Employee employee = list.get(0);
			if(employee.getUsername().equals(name))
				return employee;
		}
		return null;
	}
	
	public boolean initialEmployee(Employee employee) {
		Transaction tx = null;
		Session session = null;
		try {				
			session = this.getSession();
			tx = session.beginTransaction();
			
			Employee e = this.lookUpByUsername(employee.getUsername());
			
			if (e == null) {
				session.save(employee);
			}			
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)	tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			if(session != null)	session.close();
		}		
		return true;
	}
}


